<template>
  <div class="main-page">
    <PageSearch :search-form-config="searchFormConfig" :form-data.sync="formData" @searchBtnClick="handleSearch" />
    <PageContent ref="pageContent" :form-data="formData" :content-table-config="contentConfig">
      <template #operate="{ row }">
        <el-button type="text" size="small" icon="el-icon-edit" @click="handleCreateUser(row)">
          编辑
        </el-button>
      </template>
    </PageContent>
    <!-- 用户资料弹窗 -->
    <PageModal custom-class="custom-modal" ref="pageModal" :modal-form-data="modalFormData"
      :modal-form-config="modalFormConfig" :visible.sync="dialogVisible" title="用户资料" :btn-loading="confirmBtnLoading"
      width="60%" top="5vh" @confirm="handleConfirm" @cancel="handleCancel" @close="handleCancel">
      <el-form :model="modalFormData">
        <el-tabs v-model="activeTab">
          <!-- 实名认证 -->
          <el-tab-pane name="realName" label="实名认证">
            <el-form :model="modalFormData" :rules="realNameRules" ref="realNameForm">
              <el-row :gutter="20">
                <!-- 第一行 -->
                <el-col :span="24">
                  <el-form-item label="姓名" prop="realName">
                    <el-input v-model="modalFormData.realName" placeholder="请输入真实姓名" />
                  </el-form-item>
                </el-col>

                <!-- 第二行 -->
                <el-col :span="12">
                  <el-form-item label="身份证号" prop="idCardNo">
                    <el-input v-model="modalFormData.idCardNo" placeholder="请输入18位身份证号码" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="实名手机号" prop="phoneNumber">
                    <el-input v-model="modalFormData.phoneNumber" placeholder="请输入11位手机号码" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>

          <!-- 公司认证 -->
          <el-tab-pane name="company" label="公司认证">
            <el-row :gutter="20">
              <!-- 第一行 -->
              <el-col :span="12">
                <el-form-item label="公司名称" prop="companyName">
                  <el-input v-model="modalFormData.companyInfo.companyName" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="统一信用代码" prop="creditCode">
                  <el-input v-model="modalFormData.companyInfo.creditCode" />
                </el-form-item>
              </el-col>

              <!-- 第二行 -->
              <el-col :span="12">
                <el-form-item label="法人姓名" prop="personName">
                  <el-input v-model="modalFormData.companyInfo.personName" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法人身份证号" prop="idCardNo">
                  <el-input v-model="modalFormData.companyInfo.idCardNo" />
                </el-form-item>
              </el-col>

              <!-- 第三行 -->
              <el-col :span="12">
                <el-form-item label="法人手机号" prop="personPhone">
                  <el-input v-model="modalFormData.companyInfo.personPhone" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法人地址" prop="personAddress">
                  <el-input v-model="modalFormData.companyInfo.personAddress" />
                </el-form-item>
              </el-col>

              <!-- 第四行 -->
              <el-col :span="12">
                <el-form-item label="对公账户" prop="corporateAccount">
                  <el-input v-model="modalFormData.companyInfo.corporateAccount" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开户行" prop="openingBank">
                  <el-input v-model="modalFormData.companyInfo.openingBank" />
                </el-form-item>
              </el-col>

              <!-- 第五行 -->
              <el-col :span="12">
                <el-form-item label="发票类型" prop="invoicingType">
                  <el-input v-model="modalFormData.companyInfo.invoicingType" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开票税点" prop="taxPoint">
                  <el-input v-model="modalFormData.companyInfo.taxPoint" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 个人账户 -->
          <el-tab-pane name="accounts" label="个人账户">
            <el-table :data="accountList">
              <!-- 账户类型列 -->
              <el-table-column prop="type" label="账户类型">
                <template #default="{ row }">
                  {{ { 1: '支付宝', 2: '银行卡' }[row.type] || '未知类型' }}
                </template>
              </el-table-column>
              <el-table-column prop="idCardNo" label="身份证号">
                <template #default="{ row }">
                  <el-input v-if="row.editing" v-model="row.idCardNo" />
                  <span v-else>{{ row.idCardNo }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="cardName" label="姓名">
                <template #default="{ row }">
                  <el-input v-if="row.editing" v-model="row.cardName" />
                  <span v-else>{{ row.cardName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="phone" label="手机号">
                <template #default="{ row }">
                  <el-input v-if="row.editing" v-model="row.phone" />
                  <span v-else>{{ row.phone }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="cardNo" label="卡号/支付宝">
                <template #default="{ row }">
                  <el-input v-if="row.editing" v-model="row.cardNo" />
                  <span v-else>{{ row.cardNo }}</span>
                </template>
              </el-table-column>
              <!-- 是否默认列 -->
              <el-table-column prop="isDefault" label="是否默认">
                <template #default="{ row }">
                  <span v-if="row.editing">
                    <el-input v-model="row.isDefault" />
                  </span>
                  <span v-else>
                    {{ row.isDefault === 1 ? '是' : row.isDefault === 0 ? '否' : '' }}
                  </span>
                </template>
              </el-table-column>

              <el-table-column prop="openingBank" label="开户行">
                <template #default="{ row }">
                  <el-input v-if="row.editing" v-model="row.openingBank" />
                  <span v-else>{{ row.openingBank }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button type="text" @click="toggleEdit(row)">
                    {{ row.editing ? '保存' : '修改' }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </PageModal>
  </div>
</template>
<script>
import { contentConfig } from "./config/content.config";
import { searchFormConfig } from "./config/search.config";
import { modalFormConfig } from "./config/modal.config";
import { teamFormConfig } from "./config/teamModal.config";
import { referrerModalFormConfig } from "./config/referrerModal.config";
import _ from 'lodash';  // 添加在文件顶部

import {
  fetchRoleList,
  fetchLevelList,
  fetchRealAuthInfo,
  fetchCompanyAuthInfo,
  fetchUserAccounts,
  updateUserAccount,
  // updateAllUserInfo,
} from "@/api/useManage";
import { post, get } from "@/utils/request";
import { getUserList } from "@/api/user";
import { userTeamList } from "@/api/userTeam";
const INIT_MODAL_DATA = () => ({
  name: "",
  phone: "",
  roleIds: [],
  gradeLevel: "",
  accounts: [],  // 确保初始化为空数组
  teamId: "",
  phoneNumber: '',  // 初始化手机号
  idCardNo: '',  // 初始化身份证号
  realName: '',  // 初始化姓名
  companyInfo: {  // 从 null 改为空对象
    idCardNo: '',
    companyName: '',
    // 其他公司认证字段初始化...
  },
  accounts: []
});
export default {
  name: "User",
  data() {
    // 手机号正则（支持13/14/15/16/17/18/19开头）
    const mobilePattern = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
    // 身份证号正则（18位，最后一位可以是X）
    const idCardPattern = /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dX]$/i
    return {
      modalFormData: {},
      // 弹窗相关状态
      dialogVisible: false,
      confirmBtnLoading: false,
      activeTab: 'realName',
      accountList: [],
      modalFormData: INIT_MODAL_DATA(),

      // 配置数据
      tabConfig: [
        { label: '实名认证', name: 'realName' },
        { label: '公司认证', name: 'company' },
        { label: '个人账户', name: 'accounts' }
      ],
      realNameRules: {
        realName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名长度2-10个字符', trigger: 'blur' }
        ],
        idCardNo: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' },
          { pattern: idCardPattern, message: '请输入有效的身份证号码', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: mobilePattern, message: '请输入有效的手机号码', trigger: 'blur' }
        ]
      },
      // 页面配置
      contentConfig,
      searchFormConfig,
      modalFormConfig,
      referrerModalFormConfig,
      teamFormConfig,

      // 表单数据
      formData: {}
    };
  },
  async mounted() {
    await Promise.all([this.getTeam(), this.getUserListReq()]);
  },
  methods: {
    // 初始化弹窗数据
    initModalData() {
      this.modalFormData = INIT_MODAL_DATA();
      this.accountList = [];
      this.activeTab = 'realName';
    },
    // 处理弹窗关闭
    handleCancel() {
      this.dialogVisible = false;
      this.$nextTick(() => {
        this.initModalData();
        // 安全调用resetForm方法
        if (this.$refs.pageModal && this.$refs.pageModal.resetForm) {
          this.$refs.pageModal.resetForm();
        }
      });
    },
    // 账户编辑切换
    toggleEdit(row) {
      if (row.editing) {
        updateUserAccount(row)
          .then(() => this.$message.success('账户信息已更新'))
          .catch(() => this.$message.error('更新失败'));
      }
      this.$set(row, 'editing', !row.editing);
    },
    // 提交表单
    // async handleConfirm() {
    //   try {
    //     await this.$refs.realNameForm.validate()

    //     this.confirmBtnLoading = true;
    //     await updateAllUserInfo({
    //       realAuth: _.pick(this.modalFormData, ['realName']),
    //       companyAuth: this.modalFormData.companyInfo,
    //       accounts: this.accountList
    //     });
    //     this.$message.success('信息更新成功');
    //     this.$refs.pageContent.queryTblMain();
    //   } catch (error) {
    //     if (e?.fields) {
    //       this.$message.warning('请正确填写表单内容')
    //     } else {
    //       // ... existing error handling ...
    //     }
    //   } finally {
    //     this.confirmBtnLoading = false;
    //     this.dialogVisible = false;
    //   }
    // },
    // 打开用户资料弹窗
    // 在数据合并时添加ID字段
    async handleCreateUser(row) {
      try {
        this.dialogVisible = true;
        const [realAuth, companyAuth, accounts] = await Promise.all([
          fetchRealAuthInfo(row.id).catch(() => ({ data: {} })),
          fetchCompanyAuthInfo(row.id).catch(() => ({ data: {} })),
          fetchUserAccounts(row.id).catch(() => ({ data: [] }))
        ]);

        this.modalFormData = _.merge(
          {},
          INIT_MODAL_DATA(), // 先合并初始化结构
          {
            companyInfo: INIT_MODAL_DATA().companyInfo // 确保嵌套结构存在
          },
          {
            // 实名认证字段
            id: realAuth.data?.id,
            realName: realAuth.data?.realName || '',
            idCardNo: realAuth.data?.idCardNo || '',  // 实名身份证号
            phoneNumber: realAuth.data?.phoneNumber || '',

            // 公司认证字段
            companyInfo: {
              id: companyAuth.data?.id,
              idCardNo: companyAuth.data?.idCardNo || '',  // 公司法人身份证号
              companyName: companyAuth.data?.companyName || '',
              personName: companyAuth.data?.personName || '',
              personPhone: companyAuth.data?.personPhone || '',
              personAddress: companyAuth.data?.personAddress || '',
              creditCode: companyAuth.data?.creditCode || '',
              corporateAccount: companyAuth.data?.corporateAccount || '',
              openingBank: companyAuth.data?.openingBank || '',
              invoicingType: companyAuth.data?.invoicingType || '',
              taxPoint: companyAuth.data?.taxPoint || ''
            },
            userId: row.id
          },
          {
            accounts: accounts.data || []
          }
        );

        // 处理账户列表显示
        this.accountList = (accounts.data || []).map(account => ({
          ...account,
          id: account.id,
          cardNo: account.cardNo, // 映射API字段到表格字段
          editing: false
        }));
      } catch (e) {
        console.error('[ERROR] 数据加载失败:', e);
        this.$message.error('数据加载失败');
        this.dialogVisible = false;
      }
    },
    // 获取团队数据
    async getTeam() {
      const { data } = await userTeamList();
      const teamOptions = data.map(({ name, id }) => ({ label: name, value: id }));
      [this.searchFormConfig.formItems[1], this.teamFormConfig.formItems[0]].forEach(
        item => item.options = teamOptions
      );
    },
    handleSearch() {
      this.$refs.pageContent.queryTblMain();
    },
    async initSelect() {
      const [roles, levels] = await Promise.all([fetchRoleList(), fetchLevelList()]);
      this.modalFormConfig.formItems[2].options = roles.data?.map(({ name, id }) => ({ label: name, value: id }));
      this.modalFormConfig.formItems[3].options = levels.data?.map(({ name, level }) => ({ label: name, value: level }));
    },
    async getUserListReq() {
      const { data } = await getUserList({ pageSize: 1e4, pageNum: 1 });
      const referrerField = this.referrerModalFormConfig.formItems.find(
        item => item.field === "referrerId"
      );
      referrerField.options = data?.userList?.map(({ name, phone, id }) => ({
        label: `${name}（${phone}）`,
        value: id,
        isLeaf: true
      })) || [];
    },
    async handleConfirm() {
      try {
        this.confirmBtnLoading = true;

        // 根据当前激活的tab调用不同接口
        switch (this.activeTab) {
          case 'realName':
            await this.updateRealAuth();
            break;
          case 'company':
            await this.updateCompanyAuth();
            break;
          case 'accounts':
            await this.updateAccounts();
            break;
          default:
            throw new Error('未知的标签类型');
        }

        this.$message.success('信息更新成功');
        this.$refs.pageContent.queryTblMain();
      } catch (e) {
        this.$message.error(`保存失败: ${e.message}`);
      } finally {
        this.confirmBtnLoading = false;
        this.dialogVisible = false;
      }
    },
    // 修改保存方法确保传递ID
    async updateRealAuth() {
      const params = {
        id: this.modalFormData.id, // 从modalFormData获取实名记录ID
        userId: this.modalFormData.userId,
        ..._.pick(this.modalFormData, ['realName', 'idCardNo', 'phoneNumber'])
      };
      return post('/user/personRealName/realNameAdmin', params);
    },

    // 公司认证保存
    async updateCompanyAuth() {
      const params = {
        id: this.modalFormData.companyInfo?.id,
        userId: this.modalFormData.userId,
        ...this.modalFormData.companyInfo // 展开所有公司认证字段
      };
      return post('/user/companyReal/companyRealAdmin', params);
    },

    // 账户信息保存（已在单独编辑时保存）
    async updateAccounts() {
      return Promise.resolve(); // 账户信息在行内编辑时已单独保存
    }
  },
};

</script>
<style lang="scss" scoped>
:deep(.custom-modal) {
  width: 80% !important;
  max-width: 1200px;

  .el-dialog__body {
    padding: 20px 30px;
  }
}
</style>